package cn.bdqn.service.admin;

import cn.bdqn.dao.User.UserMapper;
import cn.bdqn.dto.LoginUser;
import cn.bdqn.pojo.User.User;
import cn.bdqn.pojo.User.User_Permission;
import cn.bdqn.service.user.PermissionService;
import cn.bdqn.service.user.UserService;
import cn.bdqn.utils.Json;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class AdminLoginService implements UserDetailsService {

    @Autowired
    private UserMapper userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        System.out.println(phone+"phone");
        //根据 账号  查询到对应的user信息
        User user = userService.getUserByPhone(phone);
        log.info("--------------user :::"+user+"----------------");
        if (Objects.isNull(user)){
            //抛出异常
            throw  new RuntimeException("用户名或密码错误");
        }
        if(user.getIsDel() == 0){
            throw new RuntimeException("您的账户异常,请联系客服核实");
        }
        //根据用户查询到对应权限
        List<User_Permission> permission = permissionService.getPermission(user.getUserId());
        System.out.println(permission);
        List<String> list = new ArrayList<>();
        for (User_Permission user_permission : permission) {
//            System.out.println(user_permission);//遍历所有权限 并设置保存到list

            list.add(user_permission.getPermission());
        }
        if(Objects.isNull(list)){
            throw new RuntimeException("您的账户异常,已被锁定,请联系客服核实");
        }
        log.info("设置权限为---------"+list.toString());
        //交给LoginUser 类处理
        return new LoginUser(user,list);
    }


}
